/**
 * Copyright (C) @2014 Webank Group Holding Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.webank.framework.data.jedis.strategy;

import java.util.HashSet;
import java.util.Set;

import com.google.common.hash.Hashing;

import cn.webank.framework.data.jedis.utils.ConsistentHash;

/**
 * 缺省选择Jedis索引服务器策略
 * 
 * @author jonyang
 *
 */
public class DefaultIndexStrategy implements IndexStrategy {
	private ConsistentHash<Integer> consistentHash = null;
	private static final int REPLICAS = 1;

	public DefaultIndexStrategy(int size) {
		Set<Integer> nodes = new HashSet<Integer>();
		for (int i = 0; i < size; i++) {
			nodes.add(i);
		}
		consistentHash = new ConsistentHash<Integer>(Hashing.murmur3_128(),
				REPLICAS, nodes);
	}

	public void add(Integer node) {
		consistentHash.add(node);
	}

	@Override
	public int getIndex(String key) {
		Integer p = consistentHash.get(key);
		for (int i = 0; i < REPLICAS; i++) {
			if (p == null) {
				p = consistentHash.getNext(key);
			} else {
				break;
			}
		}

		if (p == null)
			throw new NullPointerException("No avaliable JedisShardedPool!");

		return p;
	}
}
